﻿/*
* Activity Tracking Log v0.1.1 - http://activitytrackinglog.codeplex.com
* Activity Tracking Log for ASP.Net & ASP.Net MVC
* Copyright (c) 2011 Vadim Burac
* Licensed under the Microsoft Public License (Ms-PL)
* http://activitytrackinglog.codeplex.com/license
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ActivityTrackingLog.Data;
using System.Linq.Expressions;

namespace ActivityTrackingLog.Storage.Implementations
{
    internal class L2SqlContext : BaseContext
    {
        #region private data

        private DomainDataContext _context = null;

        #endregion

        #region ctors

        public L2SqlContext()
        {
            _context = new DomainDataContext(Configuration.Config.Storage.ConnectionString);
        }

        #endregion

        #region

        public override void ReleaseResources()
        {
            _context.Dispose();

            base.ReleaseResources();
        }

        public override void SubmitChanges()
        {
            _context.SubmitChanges();
        }

        #endregion

        #region entity related logic

        public override IQueryable<T> GetQuery<T>()
        {
            return _context.GetTable<T>().AsQueryable();
        }

        public override void Add(ActivityItem item)
        {
            SaveUserAgentItem(item);
            _context.ActivityItems.InsertOnSubmit(item);
        }

        public override void RemoveAll(Expression<Func<ActivityItem, bool>> predicate)
        {
            var itemsToDelete = _context.ActivityItems.Where(predicate).ToList();

            itemsToDelete.ForEach(item => _context.ActivityItems.DeleteOnSubmit(item));
        }

        public override int Count()
        {
            return _context.ActivityItems.Count();
        }

        #endregion

        #region helpers

        private void SaveUserAgentItem(ActivityItem item)
        {
            if (null != item.UserAgentItem)
            {
                if (item.UserAgentItem.IsNew)
                {
                    _context.UserAgentItems.InsertOnSubmit(item.UserAgentItem);
                }
                else
                {
                    var id = item.UserAgentItem.UserAgentId;
                    item.UserAgentItem = _context.UserAgentItems.Where(ua => ua.UserAgentId == id).FirstOrDefault();
                }
            }
        }

        #endregion
    }
}
